package com.itheima.exerciseTest.method50_59.method50;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;

public class Demo1 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        InputStream is = systemClassLoader.getResourceAsStream("com\\itheima\\exerciseTest\\method50_59\\method50\\student.properties");
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"gbk"));
        Properties prop = new Properties();
        prop.load(br);
        br.close();
        is.close();
        System.out.println(prop);

        // 获得类对象
        Class className = Class.forName(prop.getProperty("className"));
        // 创建对象
        Object o = className.newInstance();

        System.out.println(o);

        // 获得集合中所有的那啥
        Set<String> keys = prop.stringPropertyNames();

        // 遍历集合进行成员赋值操作
        for (String fieldName : keys) {
            if(!fieldName.equals("className")){
                // 获得属性对象
                Field field = className.getDeclaredField(fieldName);
                // 获得属性的类型
                Class type = field.getType();
                // 拼接set方法
                String methodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
                // System.out.println(methodName);
                // 获取set方法
                Method method = className.getMethod(methodName, type);

                String value = prop.getProperty(fieldName);
                if("int".equals(type.getName())){
                    int value2 = Integer.parseInt(value);
                    method.invoke(o,value2);
                }else{
                    // 执行set方法
                    method.invoke(o,value);
                }
            }
        }

        System.out.println(o);
    }

}
